package cn.bj.yu.concurrent;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicketDemo02_lock {
    public static void main(String[] args) {
        //并发：多个线程操作同一个类 把资源类丢入线程
        Ticket2 ticket = new Ticket2();

        //@FunctionalInterface 函数式接口，jdk1.8 lambda表达式(参数)->{代码}
        //匿名内部类
        new Thread(() -> { for (int i = 1; i < 110; i++) ticket.sale(); }, "A").start();
        new Thread(() -> { for (int i = 1; i < 110; i++) ticket.sale(); }, "B").start();
        new Thread(() -> { for (int i = 1; i < 110; i++) ticket.sale(); }, "C").start();
    }
}

//Lock 三部曲
// 1.Lock lock = new ReentrantLock();
// 2.lock.lock();//加锁
// 3.finally => lock.unlock();//解锁
class Ticket2 {
    //属性，方法
    private int number = 100;

    Lock lock = new ReentrantLock(false); //默认是false，非公平锁

    //买票的方式
    public void sale() {
        lock.lock();//加锁
        try {
            //业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + number-- + "票,剩余" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }
}